<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        class="mr-5px"
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['produce:production-proportion:save']"
        v-show="formType == 'edit'"
        >保 存</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <p class="baseTitle">基本信息</p>
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        label-width="80px"
        v-loading="formLoading"
      >
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="formData.orderNumber" disabled />
        </el-form-item>
        <el-form-item label="订单类型" prop="dictOrderType">
          <el-select
            v-model="formData.dictOrderType"
            placeholder="请选择订单类型"
            disabled
            class="!w-220px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="formData.customerCode" disabled />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="formData.customerName" disabled />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input v-model="formData.productStandard" disabled />
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="formData.productNumber" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="formData.productName" disabled />
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-input v-model="formData.productType" disabled />
        </el-form-item>
      </el-form>
      <p class="baseTitle">占比配置</p>
      <el-table
        :data="formData.productionProportionConfRespVOS"
        class="mt-20px tableView"
        style="width: 100%"
        row-key="id"
        border
        :default-expand-all="false"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column
          :prop="item.val"
          :label="item.label"
          :min-width="item.width"
          align="left"
          header-align="left"
          v-for="item,index in tableTitle"
          :key="index"
        >
          <template #default="scope">
            <template v-if="item.val === 'proportion'">
              <el-input-number
                v-model="scope.row[item.val]"
                :placeholder="iptTip(item.val)"
                :disabled="formType != 'edit'"
              />
            </template>
            <dict-tag v-else-if="item.val === 'dictProcessName'" type="craft_process_name" :value="scope.row.dictProcessName" />
            <div v-else>{{ scope.row[item.val] }}</div>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as ProductionProportionApi from '@/api/produce/workOrderManagement/productionProportion'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

  //占比提示
  const iptTip = (str: string) => {
    return str == 'partProportion' ? '请输入部件占比' : '请输入工序占比'
  }

  /**判定有没有输入框 */
  // const getIsIpt = (val: string, data: object) => {
  //   //表示是部件
  //   if (val == 'partProportion' && data.comProType == 1) {
  //     return true
  //   }
  //   //表示是可以编辑工序
  //   if (val == 'processProportion' && data.comProType == 2 && !data.children) {
  //     return true
  //   }
  //   return false
  // }

  /**校验占比
   * res:数据
   * needVal:需要的字段
   */
  const getTreeData = async () => {
    //部件占比
    const res = formData.value.productionProportionConfRespVOS
    for (let item of res) {
      //是部件
      if (item.comProType == 1) {
        partProportionTotal.value = 0
        breakType.value = false
        await getTotal(item.children)
        if (breakType.value) {
          message.error('工序占比不能为空')
          return false
        }
        if (partProportionTotal.value != item.partProportion) {
          return false
        }
      }
    }
    return true
  }
  //总和
  const partProportionTotal = ref(0)
  //是否为空
  const breakType = ref(false)
  //计算
  const getTotal = async (data: object) => {
    if (!data.length) {
      if (!data.children) {
        if (dataRule.value.includes(data.processProportion)) {
          breakType.value = true
        }
        partProportionTotal.value += parseFloat(data.processProportion)
      } else {
        for (let item of data.children) {
          await getTotal(item)
        }
      }
    } else {
      for (let item of data) {
        await getTotal(item)
      }
    }
  }
  /** 提交表单 */
  const dataRule = ref(['', undefined, null]) //校验规则
  const submitForm = async () => {
    //校验
    // for(let i = 0;i<)
    // 提交请求
    formLoading.value = true
    try {
      const data = {
        id: formData.value.id,
        productionProportionConfUpdateReqVOS: formData.value.productionProportionConfRespVOS
      }
      // console.log(data)
      // await ProductionProportionApi.updateProductionProportion(data)
      // return
      let partProportionNum = 0
      data.productionProportionConfUpdateReqVOS.map((item) => {
        if (dataRule.value.includes(item.proportion)) {
            message.error('部件占比不能为空')
            return
          }
          partProportionNum += parseFloat(item.proportion)
        // if (item.comProType == 1) {
        //   if (dataRule.value.includes(item.proportion)) {
        //     message.error('部件占比不能为空')
        //     return
        //   }
        //   partProportionNum += parseFloat(item.proportion)
        //   console.log()
        // }
      })
      console.log(partProportionNum)
      if (partProportionNum != 100) {
        message.error('部件占比之和必须为100%')
        return
      }
      const isFlag = await getTreeData()
      if (!isFlag) {
        message.error('工序占比之和必须等于部件工序')
        return
      }
      await ProductionProportionApi.updateProductionProportion(data)
      message.success(t('common.updateSuccess'))
      goBack()
    } finally {
      formLoading.value = false
    }
  }

  /**返回 */
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/produce/produce/workOrderManagement/productionProportion'
    })
  }
  // 获得id
  const { query } = useRoute() // 路由的查询
  /** 初始化 */
  const formType = ref('') // 详情的类型：create - 新增；update - 修改
  //详情数据
  const formData = ref({
    orderNumber: undefined,
    dictOrderType: undefined,
    customerCode: undefined,
    customerName: undefined,
    productStandard: undefined,
    productNumber: undefined,
    productName: undefined,
    productType: undefined
  })
  const tableTitle = ref([
    {
      label: '部件类型',
      val: 'partType',
      width: 300
    },
    {
      label: '工序名称',
      val: 'dictProcessName',
      width: 300
    },
    {
      label: '占比',
      val: 'proportion',
      width: 300
    }
  ])
  const contentHeight = ref(0)
  onMounted(async () => {
    formLoading.value = true
    formType.value = query.type
    if (query.id) {
      formData.value = await ProductionProportionApi.getProductionProportion(query.id)
      contentHeight.value = document.body.clientHeight - 127
    }
    formLoading.value = false
  })
</script>
<style scoped lang="scss">
  .contentView {
    padding: 10px;
    background: #fff;
  }

  .tableView {
    :deep(.el-input__wrapper) {
      // box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;

      .el-input__inner {
        cursor: default !important;
        text-align: left;
      }
    }
  }
</style>